package com.windoent.yugioh.ui.activity.saishi;

import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.baidu.mobstat.StatService;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.windoent.yugioh.MyApplication;
import com.windoent.yugioh.R;
import com.windoent.yugioh.adapter.brvah.PanFaRecordAdapter;
import com.windoent.yugioh.base.BaseActivity;
import com.windoent.yugioh.bean.PanFaListData;
import com.windoent.yugioh.constants.Constants;
import com.windoent.yugioh.http.PhoneLive;
import com.windoent.yugioh.ui.activity.meinfo.MyMsgActivity;
import com.windoent.yugioh.utils.BaseMethod;
import com.windoent.yugioh.utils.BaseUtils;
import com.windoent.yugioh.utils.LogUtils;
import com.windoent.yugioh.utils.ToastUtils;
import com.windoent.yugioh.widget.ActivityTitle;
import com.windoent.yugioh.widget.MessageItem;
import com.windoent.yugioh.widget.dialog.PanFaDetailsDialog;
import com.windoent.yugioh.widget.dialog.ShareQqWechatDialog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;

import java.util.HashMap;
import java.util.List;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.onekeyshare.OnekeyShare;
import okhttp3.Call;

/**
 * author : robert
 * date   : 2021/5/21 16:53
 * desc   :判罚详情
 */
public class PanFaDetailsActivity extends BaseActivity {
    private ActivityTitle mActivityTitle;
    private LinearLayout mLlShare;
    private MessageItem mItemMessage;
    private SmartRefreshLayout mSmartLayout;
    private RecyclerView mRecyclerView;
    private String limit = Constants.PAGETEN;
    private int mCount = 1;
    private String gameId;
    private String userId;
    private PanFaRecordAdapter adapter;

    @Override
    public int getLayout() {
        return R.layout.activity_saishi_panfa_details;
    }

    @Override
    public void initView() {
        super.initView();
        mActivityTitle = (ActivityTitle) findViewById(R.id.activity_title);
        immersiveStatusBar(mActivityTitle.getView());
        mLlShare = (LinearLayout) findViewById(R.id.ll_share);
        mItemMessage = (MessageItem) findViewById(R.id.item_message);
        mSmartLayout = (SmartRefreshLayout) findViewById(R.id.smart_layout);
        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
    }

    @Override
    public void initData() {
        super.initData();
        Intent intent = getIntent();
        gameId = intent.getStringExtra("gameId");
        userId = intent.getStringExtra("userId");
        initAdapter();
        initRefreshData();
        fresh();
    }

    @Override
    public void initListener() {
        super.initListener();
        mActivityTitle.setBackListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        mItemMessage.setListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(mContext, MyMsgActivity.class));
            }
        });
        mLlShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                shareQQWechatDialog();
            }
        });
    }

    private void initRefreshData() {
        //下拉刷新
        mSmartLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                fresh();
            }
        });
        //加载更多
        mSmartLayout.setOnLoadMoreListener(new OnLoadMoreListener() {

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                loadMore();
            }
        });
    }

    private void loadMore() {
        mCount = mCount + 1;
        getPanFaList(mCount + "", limit, false);
    }

    private void fresh() {
        mCount = 1;
        getPanFaList(mCount + "", limit, true);
    }

    private void initAdapter() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        adapter = new PanFaRecordAdapter();
        adapter.setEmptyView(LayoutInflater.from(mContext).inflate(R.layout.recycler_view_empty, mRecyclerView, false));
        adapter.setAnimationEnable(false);
        mRecyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> baseQuickAdapter, @NonNull View view, int position) {
                List<PanFaListData.DataBean.ResBean> data = adapter.getData();
                if (data != null) {
                    PanFaListData.DataBean.ResBean resBean = data.get(position);
                    if (resBean != null) {
                        String remark = resBean.getRemark();
                        if (BaseMethod.notNull(remark))
                            showDetailsPanfaDialog(remark);
                    }
                }
            }
        });
        addHeader(adapter);
    }

    private void showDetailsPanfaDialog(String remark) {
        PanFaDetailsDialog dialog = new PanFaDetailsDialog(mContext);
        dialog.setContentStr(remark);
        dialog.show();
    }

    //标题头
    private void addHeader(PanFaRecordAdapter adapter) {
        View headView = getLayoutInflater().inflate(R.layout.head_rv_view_panfa_detail_title, (ViewGroup) mRecyclerView.getParent(), false);
        if (adapter != null) {
            adapter.addHeaderView(headView);
            adapter.setHeaderWithEmptyEnable(true);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(this);
    }

    //判罚
    private void getPanFaList(String page, String limit, boolean fresh) {
        showLoadingDialog("");
        PhoneLive.getPanFaList(getUserToken(), gameId, userId, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
                freshFail(fresh);
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    try {
                        if (BaseUtils.codeIs0(mContext, response)) {
                            PanFaListData fromJson = gson.fromJson(response, PanFaListData.class);
                            if (fromJson != null) {
                                PanFaListData.DataBean data = fromJson.getData();
                                if (data != null) {
                                    List<PanFaListData.DataBean.ResBean> res = data.getRes();
                                    if (res != null) {
                                        if (fresh) {
                                            adapter.setNewInstance(res);
                                            mSmartLayout.finishRefresh(true);
                                        } else {
                                            adapter.addData(res);
                                            mSmartLayout.finishLoadMore(true);
                                        }
                                    } else freshFail(fresh);
                                } else freshFail(fresh);
                            } else freshFail(fresh);
                        } else freshFail(fresh);
                    } catch (JSONException e) {
                        freshFail(fresh);
                        e.printStackTrace();
                    }
                } else {
                    freshFail(fresh);
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }

    //刷新失败
    private void freshFail(boolean fresh) {
        if (fresh) {
            adapter.setNewInstance(null);
            mSmartLayout.finishRefresh(false);
        } else {
            mSmartLayout.finishLoadMore(false);
        }
    }

    //分享dialog
    private void shareQQWechatDialog() {
        ShareQqWechatDialog dialog = new ShareQqWechatDialog(mContext);
        dialog.setOnclickListener(new ShareQqWechatDialog.onOnclickListener() {
            @Override
            public void onClick(String name) {
                shareQQWechat(name);
            }
        });
        dialog.show();
    }

    //分享
    private void shareQQWechat(String platform) {
        OnekeyShare oks = new OnekeyShare(); //关闭sso授权 oks.disableSSOWhenAuthorize();
        //指定分享的平台，如果为空，还是会调用九宫格的平台列表界面
        if (platform != null) {
            oks.setPlatform(platform);
        }
        // title标题，微信、QQ和QQ空间等平台使用
        oks.setTitle(getString(R.string.string_share_word));
        // titleUrl QQ和QQ空间跳转链接
        oks.setTitleUrl(Constants.testWebUrl);
        // text是分享文本，所有平台都需要这个字段
        oks.setText(getString(R.string.string_add_address_warning));
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
//        oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        oks.setImageUrl("http://47.101.31.182/group1/M00/00/02/rBM8DV8ebh-ARJuGAABck3rGBcs906.png");
        // url在微信、微博，Facebook等平台中使用
        oks.setUrl(Constants.testWebUrl);
        //QQ空间
        oks.setSite(getString(R.string.app_name));
        oks.setCallback(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                ToastUtils.showText(getString(R.string.string_share_sucess));
                LogUtils.d("ShareLogin", "onComplete ---->  分享成功");
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                LogUtils.d("ShareLogin", "onError ---->  失败" + throwable.getStackTrace());
                LogUtils.d("ShareLogin", "onError ---->  失败" + throwable.getMessage());
                LogUtils.d("ShareSDK", "onError ---->  取消分享" + throwable.toString());
                throwable.printStackTrace();
                ToastUtils.showText(getString(R.string.string_share_fail));
            }

            @Override
            public void onCancel(Platform platform, int i) {
                LogUtils.d("ShareLogin", "onCancel ---->  分享取消");
            }
        });
        // 启动分享GUI
        oks.show(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        StatService.onPageStart(this, "赛事判罚详情界面");
        if (mItemMessage != null) {
            mItemMessage.setTvTitle(MyApplication.getInstance().getMsgNumber());
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        StatService.onPageEnd(this, "赛事判罚详情界面");
    }
}
